package com.trade.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.client.ItemClient;

import com.heima.client.PayClient;
import com.hmall.common.utils.BeanUtils;
import com.hmall.common.utils.RabbitMqHelper;
import com.trade.constants.MQConstants;
import com.trade.domain.dto.OrderFormDTO;
import com.trade.domain.po.Order;
import com.trade.domain.po.OrderDetail;


import com.heima.dto.ItemDTO;
import com.heima.dto.OrderDetailDTO;
import com.trade.mapper.OrderMapper;
import com.trade.service.IOrderDetailService;
import com.trade.service.IOrderService;
import com.hmall.common.exception.BadRequestException;
import com.hmall.common.utils.UserContext;


import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;


import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2023-05-05
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private final PayClient payClient;
    private final ItemClient itemClient;
    private final IOrderDetailService detailService;
    private final OrderDetailServiceImpl orderDetailServiceImpl;
    @Autowired
    private RabbitMqHelper rabbitMqHelper;

    @Override
    @GlobalTransactional
    public Long createOrder(OrderFormDTO orderFormDTO) {
        // 1.订单数据
        Order order = new Order();
        // 1.1.查询商品
        List<OrderDetailDTO> detailDTOS = orderFormDTO.getDetails();
        // 1.2.获取商品id和数量的Map
        Map<Long, Integer> itemNumMap = detailDTOS.stream()
                .collect(Collectors.toMap(OrderDetailDTO::getItemId, OrderDetailDTO::getNum));
        Set<Long> itemIds = itemNumMap.keySet();
        // 1.3.查询商品
        List<ItemDTO> items = itemClient.queryItemByIds(itemIds);
        if (items == null || items.size() < itemIds.size()) {
            throw new BadRequestException("商品不存在");
        }
        // 1.4.基于商品价格、购买数量计算商品总价：totalFee
        int total = 0;
        for (ItemDTO item : items) {
            total += item.getPrice() * itemNumMap.get(item.getId());
        }
        order.setTotalFee(total);
        // 1.5.其它属性
        order.setPaymentType(orderFormDTO.getPaymentType());
        order.setUserId(UserContext.getUser());
        order.setStatus(1);
        // 1.6.将Order写入数据库order表中
        save(order);

        // 2.保存订单详情
        List<OrderDetail> details = buildDetails(order.getId(), items, itemNumMap);
        detailService.saveBatch(details);

        // 4.扣减库存
        try {
            itemClient.deductStock(detailDTOS);
        } catch (Exception e) {
            throw new RuntimeException("库存不足！");
        }
        // 5.设计订单超时
        try {
            rabbitMqHelper.sendDelayMessage(MQConstants.DELAY_EXCHANGE_NAME, MQConstants.DELAY_ORDER_KEY, order.getId(),60000);
        } catch (Exception e) {
            log.error("订单设计超时失败，订单id：{}", order.getId(), e);
        }
        //  6.删除购物车
        try {
            rabbitMqHelper.sendMessage("trade.topic", "order.create",itemIds, UserContext.getUser());
        } catch (Exception e) {
            log.error("删除购物车失败，人id：{}， 错误id：{}",itemIds, e);
        }
        return order.getId();
    }

    @Override
    public void markOrderPaySuccess(Long orderId) {
        Order order = new Order();
        order.setId(orderId);
        order.setStatus(2);
        order.setPayTime(LocalDateTime.now());
        updateById(order);
    }

    @Override
    public void cancelOrder(Long orderId) {
        //1.修改业务订单状态
        lambdaUpdate()
                .eq(orderId!=null,Order::getId, orderId)
                .set(Order::getStatus, 5)
                .update();

        //2.修改支付订单详情状态
        payClient.updatePayOrderBystatus(orderId);
        //3.修改库存
        //根据id拿到详细
        List<OrderDetail> list = orderDetailServiceImpl.lambdaQuery()
                .eq(OrderDetail::getOrderId, orderId)
                .list();
        List<OrderDetailDTO> orderDetailDTOS = BeanUtils.copyList(list, OrderDetailDTO.class);
        orderDetailDTOS.forEach(orderDetailDTO -> {
            orderDetailDTO.setNum(-orderDetailDTO.getNum());
        });
        itemClient.deductStock(orderDetailDTOS);
    }

    private List<OrderDetail> buildDetails(Long orderId, List<ItemDTO> items, Map<Long, Integer> numMap) {
        List<OrderDetail> details = new ArrayList<>(items.size());
        for (ItemDTO item : items) {
            OrderDetail detail = new OrderDetail();
            detail.setName(item.getName());
            detail.setSpec(item.getSpec());
            detail.setPrice(item.getPrice());
            detail.setNum(numMap.get(item.getId()));
            detail.setItemId(item.getId());
            detail.setImage(item.getImage());
            detail.setOrderId(orderId);
            details.add(detail);
        }
        return details;
    }


}
